package cn.me.alphamq.broker.config;

import cn.me.alphamq.common.enumeration.BrokerModeEnum;
import cn.me.alphamq.common.enumeration.BrokerRoleEnum;
import cn.me.alphamq.common.util.PropertiesUtil;

import java.util.Properties;

/**
 * broker 集群的配置类
 *
 * @author f
 */
public class ClusterProperties {

    /**
     * broker 的模式
     */
    private final BrokerModeEnum brokerMode;

    /**
     * broker 的角色，在集群模式下，当主节点宕机时，可能会由 从节点 变成 主节点
     */
    private BrokerRoleEnum brokerRole;

    /**
     * broker 的组名
     */
    private final String brokerGroup;

    public ClusterProperties(String brokerMode, String brokerRole, String brokerGroup) {
        this.brokerMode = BrokerModeEnum.of(brokerMode);
        this.brokerRole = BrokerRoleEnum.of(brokerRole);
        this.brokerGroup = brokerGroup;
    }

    /**
     * 根据 properties 加载一个集群配置的对象
     *
     * @param properties 配置对象
     * @return 填充配置的对象
     */
    public static ClusterProperties load(Properties properties) {
        return new ClusterProperties(
                PropertiesUtil.getNotNullProperty(properties, "broker.cluster.mode"),
                PropertiesUtil.getNotNullProperty(properties, "broker.cluster.role"),
                PropertiesUtil.getNullableProperty(properties, "broker.cluster.group")
        );
    }

    public BrokerModeEnum getBrokerMode() {
        return brokerMode;
    }

    public BrokerRoleEnum getBrokerRole() {
        return brokerRole;
    }

    public String getBrokerGroup() {
        return brokerGroup;
    }

    /**
     * 将本节点的角色从 从节点 设置为 主节点，用于主从切换
     */
    public void setMasterRole() {
        this.brokerRole = BrokerRoleEnum.MASTER;
    }
}
